<script setup lang="ts">
import { ref, watch } from 'vue';
import { deviceHooks } from '@/views/breedingManage/deviceManage/deviceHooks';
import { userDevicePermissionApi } from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
const projectStore = useProjectStore();
defineOptions({
  name: 'UserAuthorityDrawer'
});

const visible = defineModel<boolean>('visible', {
  default: false
});

const authorityUserId = defineModel<number | undefined>('authorityUserId', {
  default: undefined
});

const title = '分配设备权限';

function closeDrawer() {
  visible.value = false;
  authorityUserId.value = undefined;
}

const deviceList = ref([]);
const targetKeys = ref([]);

const initDeviceList = async () => {
  const { getDeviceList } = deviceHooks();
  const userData = await getDeviceList({
    projectId: projectStore.currentProject?.id,
    userId: authorityUserId.value
  });
  targetKeys.value = userData.map((item: any) => item.id);
  const allData = await getDeviceList({
    projectId: projectStore.currentProject?.id
  });
  deviceList.value = allData.map((item: any) => {
    return {
      key: item.id,
      title: item.assetName,
      assetName: item.assetName
    };
  });
};

async function handleSubmit() {
  const res = await userDevicePermissionApi({
    userId: authorityUserId.value,
    permissions: targetKeys.value
  });
  if (res.error === null) {
    window.$message?.success('设备权限分配成功');
    closeDrawer();
  }
}

watch(visible, () => {
  if (visible.value) {
    initDeviceList();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="title" :width="560" :maskClosable="false">
    <ATransfer
      v-model:target-keys="targetKeys"
      :data-source="deviceList"
      :render="item => item.assetName"
      pagination
      class="min-h-400px"
    />
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">取消</AButton>
        <AButton type="primary" @click="handleSubmit">确认</AButton>
      </ASpace>
    </template>
  </AModal>
</template>

<style scoped></style>
